package com.itheima.reggie.common;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @author Lff
 * @date 2022/3/1
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class DownloadController {
    @Value("${reggie.imgPath}")
    private String prefPath;

    /**
     * 文件下载  也就是页面加载图片的方法
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse resp) throws IOException {
        //获取本地IO流读取文件
        File file = new File(prefPath + name);
        //使用缓冲流读取本地文件
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        //获取网络输出流
        ServletOutputStream sos = resp.getOutputStream();
        //将文件写到页面
        int len;
        byte[] bs = new byte[2048];
        while ((len = bis.read(bs)) != -1) {
            sos.write(bs, 0, bs.length);
        }
        sos.flush();
        sos.close();
        bis.close();
    }

    /**
     * 文件上传
     *
     * @param file 拿到的封装了文件的参数
     */

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        //获取原文件名的后缀 + uuid生成一个新的文件名 asd.aaa.jpg
        String oldName = file.getOriginalFilename();
        String fileSuffix = oldName.substring(oldName.lastIndexOf("."));
        String newName = UUID.randomUUID() + fileSuffix;
//        log.info("新的文件名：{}",newName);
        //创建目录
        File f = new File(prefPath);
        if (!f.exists()) { //判断这个目录是否存在
            f.mkdirs(); //不存在 创建
        }
        //保存到本地
        try {
            file.transferTo(new File(prefPath + newName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(newName);
    }
}
